// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
// Page d'identification d'un membre (cible du code QR de la carte) :
// grande photo, identité complète, badge de vérification. Le courriel et
// les coordonnées ne sont jamais exposés.
import type { Metadata } from "next";
import { db } from "@/lib/db";
import { roleLabel } from "@/lib/roles";

export const metadata: Metadata = {
  title: "Identification de membre | Groupe KA",
  description: "Identification d'un membre du Groupe KA par son KA-ID.",
  robots: { index: false },
};

export const dynamic = "force-dynamic";

function fmtDate(iso: string | null): string {
  if (!iso) return "—";
  const d = new Date(iso.includes("T") ? iso : iso.replace(" ", "T") + "Z");
  if (Number.isNaN(d.getTime())) return "—";
  return d
    .toLocaleDateString("fr-CA", { day: "numeric", month: "long", year: "numeric" })
    .replace(/^1 /, "1ᵉʳ ");
}

export default async function IdentificationMembre({
  params,
}: {
  params: Promise<{ kaId: string }>;
}) {
  const { kaId } = await params;
  const clean = /^ka-\d{10}$/.test(kaId) ? kaId : null;
  const row = clean
    ? (db
        .prepare(
          "SELECT ka_id, name, avatar_url, google_sub, role, created_at, last_login FROM users WHERE ka_id = ?",
        )
        .get(clean) as
        | {
            ka_id: string;
            name: string;
            avatar_url: string | null;
            google_sub: string | null;
            role: string | null;
            created_at: string;
            last_login: string | null;
          }
        | undefined)
    : undefined;

  if (!row) {
    return (
      <main className="mx-auto max-w-md px-4 pb-16 sm:px-6">
        <section className="pt-12 text-center sm:pt-14">
          <p className="kicker rise justify-center">Identification de membre</p>
          <h1 className="gk-display rise mt-4 text-[clamp(28px,5vw,40px)] leading-[1.02] font-bold tracking-[-0.035em] uppercase [animation-delay:0.08s]">
            Identifiant <span className="outline-txt">introuvable</span>
          </h1>
          <p className="rise mt-4 text-[14px] text-ink-2 [animation-delay:0.16s]">
            Aucun membre ne porte cet identifiant. Vérifiez le code, ou{" "}
            <a href="/connexion" className="underline underline-offset-4">
              créez votre KA ID
            </a>
            .
          </p>
        </section>
      </main>
    );
  }

  const infos: [string, string][] = [
    ["Identifiant membre", row.ka_id],
    ...(roleLabel(row.role)
      ? ([["Statut", roleLabel(row.role)!]] as [string, string][])
      : []),
    ["Membre depuis", fmtDate(row.created_at)],
    ["Dernière connexion", fmtDate(row.last_login)],
    ["Compte", row.google_sub ? "Lié à Google" : "Courriel vérifié"],
    ["Valide sur", "Les 7 plateformes ·Ka"],
  ];

  return (
    <main className="mx-auto max-w-md px-4 pb-16 sm:px-6">
      <section className="pt-10 text-center sm:pt-12">
        <p className="kicker rise justify-center">Identification de membre</p>

        {/* ——— La grande photo ——— */}
        <div className="rise mt-7 flex justify-center [animation-delay:0.08s]">
          {row.avatar_url ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={row.avatar_url}
              alt={`Photo de ${row.name}`}
              width={176}
              height={176}
              referrerPolicy="no-referrer"
              className="h-44 w-44 rounded-full border-[3px] border-ink object-cover shadow-[8px_8px_0_rgba(20,24,20,0.18)]"
            />
          ) : (
            <span className="gk-display flex h-44 w-44 items-center justify-center rounded-full border-[3px] border-ink bg-lime text-[64px] font-bold shadow-[8px_8px_0_rgba(20,24,20,0.18)]">
              {row.name.charAt(0).toUpperCase()}
            </span>
          )}
        </div>

        <h1 className="gk-display rise mt-6 text-[clamp(28px,6vw,42px)] leading-[1.02] font-bold tracking-[-0.03em] [animation-delay:0.14s]">
          {row.name}
        </h1>
        <p className="rise mt-3 inline-flex items-center gap-2 rounded-full border-[1.5px] border-ink bg-lime px-4 py-[7px] text-[13px] font-bold [animation-delay:0.2s]">
          <span
            aria-hidden="true"
            className="flex h-[18px] w-[18px] items-center justify-center rounded-full bg-ink text-[11px] font-bold text-lime"
          >
            ✓
          </span>
          Membre vérifié du Groupe KA
        </p>

        {/* ——— KA-ID ——— */}
        <div className="gk-card rise mt-7 !bg-ink p-6 text-paper [animation-delay:0.26s]">
          <p className="gk-mono text-[10px] tracking-[0.2em] uppercase text-[rgba(217,242,107,0.65)]">
            KA-ID
          </p>
          <p className="gk-mono mt-2 text-[clamp(22px,6vw,30px)] font-bold tracking-[0.14em] text-lime [text-shadow:0_0_24px_rgba(217,242,107,0.35)]">
            {row.ka_id}
          </p>
        </div>

        {/* ——— Toutes les infos ——— */}
        <div className="gk-card rise mt-5 p-0 text-left [animation-delay:0.32s]">
          {infos.map(([label, value], i) => (
            <div
              key={label}
              className={`flex items-baseline justify-between gap-4 px-5 py-[13px] ${i < infos.length - 1 ? "border-b border-dashed border-[rgba(20,24,20,0.18)]" : ""}`}
            >
              <span className="klabel flex-none">{label}</span>
              <span
                className={`text-right text-[13.5px] font-semibold ${label === "Identifiant membre" ? "gk-mono text-green" : ""}`}
              >
                {value}
              </span>
            </div>
          ))}
        </div>

        <p className="mt-5 text-[12.5px] text-ink-2">
          Cette page confirme l&apos;identité d&apos;un membre à partir du code
          QR de sa carte. Le courriel et les coordonnées ne sont jamais
          affichés.
        </p>
        <a href="/" className="btn btn-ghost mt-4">
          groupe-ka.com ↗
        </a>
      </section>
    </main>
  );
}
